<template>
  <el-popover
    placement="bottom"
    width="300"
    v-model="popoverVisible"
    trigger="click"
    popper-class="tag-customer-selector"
    @show="openPanel"
  >
    <div class="search-box">
      <el-input v-model="keyword" placeholder="搜索关键字" prefix-icon="el-icon-search" @keyup.native.enter="search">
        <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
      </el-input>
    </div>
    <div class="selector-content tag-scrollbar" v-if="groupList.length">
      <el-collapse v-model="activeCollapse" accordion>
        <el-collapse-item v-for="(item, index) in groupList" :key="item.groupId" :name="item.groupId">
          <div slot="title" class="group-title">
            <i
              class="icon-toggle"
              :class="activeCollapse === item.groupId ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
            ></i>
            <el-tooltip effect="dark" :content="item.groupNm" placement="top-start">
              <span class="name">{{ item.groupNm }}</span>
            </el-tooltip>
          </div>
          <div class="customer-list">
            <template v-if="item.page.results.length">
              <ul class="list-wrap">
                <li class="list-item" v-for="cust in item.page.results" :key="cust.tagId" @click="selectItem(cust)">
                  <icon-svg name="iconResTeam"></icon-svg>
                  <span class="list-name elli">{{ cust.derivedName }}</span>
                  <i class="el-icon-check" v-if="isSelect(cust.tagId)"></i>
                </li>
              </ul>
              <el-pagination
                style="text-align: right"
                :current-page="item.page.params.currentPageNum"
                :page-size="item.page.params.pageSize"
                background
                layout="total, prev, pager, next"
                :total="item.page.totalSize"
                :pager-count="5"
                small
                @current-change="handleCurrentChange($event, index)"
              >
              </el-pagination>
            </template>
            <div class="no-record" v-else>暂无客群</div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <p v-else>暂无分组</p>
    <div class="selector-handler">
      <el-col :span="24" align="right">
        <el-button size="mini" @click="handleCancel">取消</el-button>
        <el-button type="primary" size="mini" @click="handleConfirm">确定</el-button>
      </el-col>
    </div>
    <span slot="reference" class="customerNm">{{ custInfo.selectCust.length ? showCust : '请选择' }}</span>
  </el-popover>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  props: {
    custInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      popoverVisible: false,
      keyword: '',
      activeCollapse: -1,
      groupList: [],
      selectCust: []
    }
  },
  watch: {
    activeCollapse() {
      this.getTags()
    }
  },
  computed: {
    showCust() {
      let custNm = []
      this.custInfo.selectCust.forEach(item => custNm.push(item.derivedName))
      return custNm.join(',')
    }
  },
  methods: {
    isSelect(id) {
      return this.selectCust.find(item => item.tagId === id)
    },
    openPanel() {
      this.selectCust = cloneDeep(this.custInfo.selectCust)
      if (this.groupList.length) return
      this.getResults()
    },
    getTags() {
      const group = this.groupList.find(item => item.groupId === this.activeCollapse)
      const index = this.groupList.findIndex(item => item.groupId === this.activeCollapse)
      if (group) {
        let params = group.page.params
        if (this.keyword) params.queryParams.derivedName = this.keyword
        this.$ajax({
          url: this.$ajax.setUrl('ast/astTagDerivedGroup/getDerivesPage'),
          method: 'get',
          params: this.$ajax.setParams(group.page.params)
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.groupList[index].page.results = data.data.records
            this.groupList[index].page.totalSize = data.data.totalSize
            this.$forceUpdate()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      }
    },
    searchMyDerived(text = '') {
      // 搜索客群
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedGroup/searchMyDerived'),
        method: 'get',
        params: this.$ajax.setParams({
          tagNm: text
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = data.data
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handleCurrentChange(num, index) {
      this.groupList[index].page.params.currentPageNum = num
      this.getTags()
    },
    search() {
      this.activeCollapse = ''
      if (!this.keyword) {
        this.getResults()
      } else {
        this.searchMyDerived(this.keyword)
      }
    },
    getResults() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedGroup/getAllGroup/1'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = [{ groupId: 0, groupNm: '默认分组' }, ...data.data]
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          this.activeCollapse = 0
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    clearSearch() {
      this.keyword = ''
      this.search()
    },
    selectItem(item) {
      const index = this.selectCust.findIndex(cust => cust.tagId === item.tagId)
      if (index < 0) {
        this.selectCust.push({ tagId: item.tagId, derivedName: item.derivedName })
      } else {
        this.selectCust.splice(index, 1)
      }
    },
    handleCancel() {
      this.keyword = ''
      this.groupList = []
      this.selectCust = []
      this.activeCollapse = -1
      this.popoverVisible = false
    },
    handleConfirm() {
      this.$emit('confirm', cloneDeep(this.selectCust))
      this.popoverVisible = false
    }
  }
}
</script>

<style lang="scss">
.customerNm {
  display: inline-block;
  max-width: 90%;
  padding: 3px 15px;
  margin-top: -5px;
  border: 1px solid #eee;
  border-radius: 2px;
  color: #6a86cc;
  background-color: #e6eeff;
  word-break: break-all;
  cursor: pointer;
  &:hover {
    border-color: #6a86cc;
  }
}
.tag-customer-selector {
  height: 520px;
  padding: 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.4);
  .search-box {
    padding: 10px 20px;
    .el-input__inner {
      border-radius: 20px;
    }
    .el-input__suffix {
      top: 6px;
      right: 25px !important;
    }
    .el-input__suffix-inner {
      font-size: 18px;
      color: #4d82e9;
    }
  }
  .selector-content {
    height: calc(100% - 100px);
    overflow-y: auto;
  }
  .el-collapse-item__header {
    font-size: 16px;
    height: 45px;
    padding: 0 10px;
    line-height: 45px;
    &:hover {
      background-color: #efefef;
    }
  }
  .el-collapse-item__arrow {
    display: none;
  }
  .icon-toggle {
    font-size: 18px;
    color: #4d82e9;
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
  .customer-list {
    padding: 0 10px;
    .list-wrap li {
      padding: 0 10px;
      line-height: 30px;
      cursor: pointer;
      position: relative;
      svg {
        margin-right: 10px;
      }
      &:hover {
        color: $theme-color;
        background-color: #ddd;
      }
      i {
        font-size: 16px;
        font-weight: bold;
        color: $tag-green;
        position: absolute;
        top: 5px;
        right: 10px;
      }
    }
  }
  .selector-handler {
    border-top: 1px solid #ddd;
    padding: 5px 10px;
  }
}
</style>
